//
//  DocumentDetailViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2019/1/24.
//  Copyright © 2019年 HCreater. All rights reserved.
//

#import "DocumentDetailViewController.h"

#import "MHNavigationController.h"

@interface DocumentDetailViewController () <UIWebViewDelegate>

/// 模型视图
@property (nonatomic, readonly, strong) DocumentDetailViewModel* viewModel;

// UI
@property (nonatomic, strong) MBProgressHUD* _downloadHUBView;

//IBOutlet
@property (weak, nonatomic) IBOutlet UIView* avatarBgView;
@property (weak, nonatomic) IBOutlet UIImageView* avatarImgView;
@property (weak, nonatomic) IBOutlet UILabel* nameLabel;
@property (weak, nonatomic) IBOutlet UIView* tagView;
@property (weak, nonatomic) IBOutlet UIWebView* webView;
@property (weak, nonatomic) IBOutlet UIButton* shareBtn;
@property (weak, nonatomic) IBOutlet UIImageView* shareImgView;
@property (weak, nonatomic) IBOutlet UIButton* collectBtn;
@property (weak, nonatomic) IBOutlet UIImageView* collectImgView;

@end

@implementation DocumentDetailViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* willDisAppearSignal = [[self rac_signalForSelector:@selector(viewWillDisappear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        [self _appearChange];
    }];
    
    [willDisAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        [self _disappearChange];
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        [self.viewModel.reqDetailCmd execute:nil];
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[willAppearSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
    {
        [MBProgressHUD mh_showProgressHUD:@""];
    }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:didAppearSignal] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    [[RACObserve(self.viewModel, isCollect) deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        BOOL isCollect = [x boolValue];
        
        if (isCollect)
            [self.collectImgView setImage:MHImageNamed(@"zan_hx")];
        else
            [self.collectImgView setImage:MHImageNamed(@"icon_zan_white")];
    }];
    [[self.collectBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self.viewModel.requestCollectCmd execute:nil];
    }];
    
    [[self.shareBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_showTips:@"功能暂未开放"];
     }];
    
    [[self.viewModel.reqDetailCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_hideHUD];
         
         [self _updateAllView];
     }];
    [[self.viewModel.reqDetailCmd.errors deliverOnMainThread] subscribeNext:^(NSError* error)
     {
         @strongify(self);
         
         [MBProgressHUD mh_hideHUD];
         
         /// 处理验证错误的error
         if ([error.domain isEqualToString:SUCommandErrorDomain]) {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return ;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
    
    [[[self.viewModel.checkDownloadCmd.executing deliverOnMainThread] skip:1] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //这里的x是一个带有数据的信号,若这个信号存在那么就说明command还在执行,否则说明没有执行或者执行完毕
         if ([x boolValue])
         {
             NSLog(@"正在执行");
             
             self._downloadHUBView = [MBProgressHUD mh_showProgressHUD:@""];
         }
         else
         {
             NSLog(@"执行未开始/执行完毕");
         }
     }];
    
    [[self.viewModel.checkDownloadCmd.errors deliverOnMainThread] subscribeNext:^(NSError* error)
     {
         @strongify(self)
         
         if ([error.domain isEqualToString:SUCommandErrorDomain])
         {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
    
    [[[self.viewModel.downloadCmd.executing deliverOnMainThread] skip:1] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //这里的x是一个带有数据的信号,若这个信号存在那么就说明command还在执行,否则说明没有执行或者执行完毕
         if ([x boolValue])
         {
             NSLog(@"正在执行");
             
             self._downloadHUBView = [MBProgressHUD mh_showProgressHUD:@"下载中。。。"];
         }
         else
         {
             NSLog(@"执行未开始/执行完毕");
         }
     }];
    
    [self.viewModel.downloadCmd.executionSignals subscribeNext:^(RACSignal* signal)
     {
         @strongify(self)
         
         @weakify(self)
         [[signal deliverOnMainThread] subscribeNext:^(id x)
          {
              @strongify(self)
              
              if ([x isKindOfClass:[NSNumber class]])
              {
                  NSString* strTip = HCStrFormat(@"下载中。。。%d%%", (int)([x floatValue]*100));
                  
                  if (self._downloadHUBView)
                  {
                      self._downloadHUBView.detailsLabel.text = strTip;
                  }
              }
          } completed:^
          {
              [MBProgressHUD mh_hideHUD];
              [MBProgressHUD mh_showTips:@"文件已经保存在默认下载目录中"];
              
              ArticleInfoData* articleInfoData = self.viewModel.data;
              
              DataManager* dataMgr = [DataManager sharedDataManager];
              [dataMgr saveOfflineFileHistory:[articleInfoData dbData]];
          }];
     }];
}

#pragma mark - 更新初始化 操作
- (void)_appearChange
{
    // 导航栏颜色修改
    [self.navigationController.navigationBar setBackgroundImage:[MHNavigationController navGradientImageWithBounds:(CGRect) {0, 0, [UIScreen mainScreen].bounds.size.width, 1} andColors:@[UIColorHex(#008f58), UIColorHex(#008f58)] andGradientType:1] forBarMetrics:UIBarMetricsDefault];
    
    // 返回按钮
    UIButton* backBtn = [self.navigationItem.leftBarButtonItem.customView viewWithTag:999];
    [backBtn setImage:MHImageNamed(@"icon_back") forState:UIControlStateNormal];
    [backBtn setImage:MHImageNamed(@"icon_back") forState:UIControlStateSelected];
    
    // Title
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSFontAttributeName] = MHRegularFont_18;
    textAttrs[NSForegroundColorAttributeName] = MHGlobalWhiteTextColor;
    // UIOffsetZero是结构体, 只要包装成NSValue对象, 才能放进字典\数组中
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowOffset =  CGSizeZero;
    textAttrs[NSShadowAttributeName] = shadow;
    [self.navigationController.navigationBar setTitleTextAttributes:textAttrs];
}
- (void)_disappearChange
{
    // 导航栏颜色修改
    [self.navigationController.navigationBar setBackgroundImage:[MHNavigationController navGradientImageWithBounds:(CGRect) {0, 0, [UIScreen mainScreen].bounds.size.width, 1} andColors:@[UIColorHex(#FFFFFFFF), UIColorHex(#FFFFFFFF)] andGradientType:1] forBarMetrics:UIBarMetricsDefault];
    
    // 返回按钮
    UIButton* backBtn = [self.navigationItem.leftBarButtonItem.customView viewWithTag:999];
    [backBtn setImage:MHImageNamed(@"icon_back_hei") forState:UIControlStateNormal];
    [backBtn setImage:MHImageNamed(@"icon_back_hei") forState:UIControlStateSelected];
    
    // Title
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSFontAttributeName] = MHRegularFont_18;
    textAttrs[NSForegroundColorAttributeName] = MHGlobalBlackTextColor;
    // UIOffsetZero是结构体, 只要包装成NSValue对象, 才能放进字典\数组中
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowOffset =  CGSizeZero;
    textAttrs[NSShadowAttributeName] = shadow;
    [self.navigationController.navigationBar setTitleTextAttributes:textAttrs];
}

- (void)_setupAllView
{
    @weakify(self);
    
    self.avatarBgView.layer.cornerRadius = self.avatarBgView.frame.size.height/2.0f;
    self.avatarBgView.layer.masksToBounds = YES;
    
    self.avatarImgView.layer.cornerRadius = self.avatarImgView.frame.size.height/2.0f;
    self.avatarImgView.layer.masksToBounds = YES;
    
    self.tagView.layer.cornerRadius = self.tagView.frame.size.height/2.0f;
    self.tagView.layer.masksToBounds = YES;
}

- (void)_updateAllView
{
    @weakify(self);
    
    self.title = self.viewModel.title;
    
    self.nameLabel.text = self.viewModel.name;
    
    [self.avatarImgView yy_setImageWithURL:[NSURL URLWithString:self.viewModel.avatarImg] placeholder:MHImageNamed(@"placeholderLogo")];
    
    self.webView.scrollView.bounces = NO;
    self.webView.delegate = self;
    self.webView.scalesPageToFit = YES;
    
    if (self.viewModel.downloadFilePath && [self.viewModel.downloadFilePath isNotBlank])
    {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.viewModel.downloadFilePath]]];
        
        UIView* downloadNavView = [[UIView alloc] initWithFrame:(CGRect) {0, 0, 54.0f, 44.0f}];
        {
            UIImageView* iconImgView = [[UIImageView alloc] initWithFrame:(CGRect) {0, 0, 54, 26}];
            iconImgView.image = MHImageNamed(@"icon_xiazai_white");
            iconImgView.contentMode = UIViewContentModeCenter;
            [downloadNavView addSubview:iconImgView];
            
            UILabel* label = [[UILabel alloc] initWithFrame:(CGRect) {0, CGRectGetMaxY(iconImgView.frame), 54, 18}];
            label.font = [UIFont systemFontOfSize:10.0f];
            label.text = @"下载文档";
            label.textColor = [UIColor whiteColor];
            label.textAlignment = NSTextAlignmentCenter;
            [downloadNavView addSubview:label];
            
            UIButton* tickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            tickBtn.frame = (CGRect) {0, 0, 54, 44};
            tickBtn.tag = 10;
            [downloadNavView addSubview:tickBtn];
            
            RACSignal* downloadBtnSignal = [tickBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
            [downloadBtnSignal subscribeNext:^(id x) {
                
                @strongify(self);
                
                [self _btnListener_download];
            }];
        }
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:downloadNavView];
    }
}

#pragma mark - 功能
- (void)_btnListener_download
{
    if (self.viewModel.downloadNeedCoin > 0)
    {
        //弹出选择框
        NSString* strMsg = HCStrFormat(@"下载将消耗生态币数量:%d", (int)self.viewModel.downloadNeedCoin);
        [UIAlertView bk_showAlertViewWithTitle:@"下载提示" message:strMsg cancelButtonTitle:@"取消" otherButtonTitles:@[@"下载"] handler:^(UIAlertView *alertView, NSInteger buttonIndex)
         {
             if (buttonIndex == 1)
             {
                 [self.viewModel.checkDownloadCmd execute:nil];
             }
         }];
    }
    else
    {
        [self.viewModel.downloadCmd execute:nil];
    }
}

#pragma mark - 跳转

@end
